#import "HttpConnection.h"

#import "HttpCommucationEngineer.h"
#import "Constant.h"
#import "DictionaryUtil.h"
@implementation CHttpConnection
-init
{
	self=[super init];
	if(self)
	{
		iFlag=0;
		iControlId=0;
		iReceivedData=NULL;
		iMessageId=NULL;
		iConnection=NULL;
		iTotalLength=0;
	}
	return self;
}
- (void)HttpRequest:(NSString*)aUrl tag_UriPrefix:(NSString*)aHostUriPrefix tag_Method:(int)aMethod tag_Data:(NSString*)aData tag_ControlId:(id)aControlId tag_Flag:(int)aFlag tag_Pos:(int)aPos
{
	unsigned char *dataCString;
	NSMutableString *aUrlNew;
	NSString* requstData;
	int dataLength;
	unichar ch;
	NSData *postData;
	dataLength=0;
	iFlag=aFlag;
	iControlId=aControlId;
	aUrlNew = [[NSMutableString alloc] init];
	if(aHostUriPrefix)
	{
		if([aUrl length]>0)
			ch=[aUrl characterAtIndex:0];
		/*if(ch!='/')
		{
			[aUrlNew appendString:[aHostUriPrefix stringByAppendingString:[@"/"stringByAppendingString:aUrl]]];
		}else
		{
			[aUrlNew appendString:[aHostUriPrefix stringByAppendingString:aUrl]];
		}*/
		NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
		if(aMethod ==0)
		{
			NSLog(@"%@",aUrl);
			[request setURL:[NSURL URLWithString:aUrl]];  
			
			[request setHTTPMethod:@"GET"]; 
			
		}
		else 
		{
			NSRange rang = [aUrlNew rangeOfString:@"?"];
			aUrl = [aUrlNew substringToIndex:rang.location];
			requstData = [aUrlNew substringFromIndex:rang.location + 1];
			if (requstData) 
			{
				if (aData) 
				{
					rang.location = 0;
					rang.length = [aUrlNew length];
					[aUrlNew deleteCharactersInRange:rang];
					[aUrlNew appendString:requstData];
					[aUrlNew appendString:@"&"];
					[aUrlNew appendString:aData];
					aData = aUrlNew;
				}
				else 
				{
					aData = requstData;
				}
			}
			if(aData)
			{
				const char * utf8 = [aData UTF8String];
				dataLength = strlen(utf8);
				dataCString=(unsigned char*)utf8;
				postData=[NSData dataWithBytesNoCopy:dataCString length:dataLength freeWhenDone:YES];
				NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
				[request setURL:[NSURL URLWithString:aUrl]];  
				[request setHTTPMethod:@"POST"]; 
				[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
				[request setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];  
				[request setHTTPBody:postData]; 
			}		
		}
		[request setValue:@"do1_mm_iphone" forHTTPHeaderField:@"User-Agent"]; 
		if(aFlag&4&&aPos)
		{
			NSString *posString=[NSString stringWithFormat:@"%@%d-",@"bytes=",aPos];
			[request setValue:posString forHTTPHeaderField:@"Range"]; 
		}
		NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];  
		if (conn)    
		{  
			iReceivedData = [[NSMutableData data] retain]; 
			iConnection=conn;
		}    
		
	}

		
		[aUrlNew release];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse*)response;
	int stausCode=[httpResponse statusCode];
	NSDictionary *allHeaderFields=NULL;
	allHeaderFields=[httpResponse allHeaderFields];
	if(stausCode==206)
	{
		NSString *range=[allHeaderFields objectForKey:@"Content-Range"];
		NSRange rang = [range rangeOfString:@"/"];
		iTotalLength = [[range substringFromIndex:rang.location + 1] intValue];
	}else if((iFlag&0x3)==1)
	{
		NSString *length=[allHeaderFields objectForKey:@"Content-Length"];
		iTotalLength=[length intValue];
	}
	
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	//char a=iFlag&0x3;
	if((iFlag&0x3)==1)
	{
		unsigned char *cData=(unsigned char*)(data.bytes);
		int length=[data length];
		NSMutableDictionary *aUserInfo;
		aUserInfo=[[NSMutableDictionary alloc] init];
		[CDictionaryUtil SetIntValue:aUserInfo tagKey:@"err" tagIntValue:0];
		[CDictionaryUtil SetPointerValue:aUserInfo tagKey:@"data" tagPointerValue:cData];
		[CDictionaryUtil SetIntValue:aUserInfo tagKey:@"dataSize" tagIntValue:length];
		[CDictionaryUtil SetIntValue:aUserInfo tagKey:@"totalSize" tagIntValue:iTotalLength];
		[CDictionaryUtil SetIntValue:aUserInfo tagKey:@"type" tagIntValue:1];
		if(iControlId)
			[aUserInfo setObject:iControlId forKey:@"controlId"];
		[[NSNotificationCenter defaultCenter] postNotificationName:KNotificationHttpRecvResponse object:Nil userInfo:aUserInfo];
		
	}else {
		
		[iReceivedData appendData:data];
	}
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	if((iFlag&0x3)==1)
	{
	    NSMutableDictionary *aUserInfo;
		aUserInfo=[[NSMutableDictionary alloc] init];
		[CDictionaryUtil SetIntValue:aUserInfo tagKey:@"type" tagIntValue:2];
		if(iControlId)
			[aUserInfo setObject:iControlId forKey:@"controlId"];
		[[NSNotificationCenter defaultCenter] postNotificationName:KNotificationHttpRecvResponse object:Nil userInfo:aUserInfo];
		[aUserInfo release];
	}else {
		unsigned char *data=(unsigned char*)(iReceivedData.bytes);
	    int length=[iReceivedData length];
		NSMutableDictionary *aUserInfo;
		aUserInfo=[[NSMutableDictionary alloc] init];
		[CDictionaryUtil SetIntValue:aUserInfo tagKey:@"err" tagIntValue:0];
		[CDictionaryUtil SetPointerValue:aUserInfo tagKey:@"data" tagPointerValue:data];
		[CDictionaryUtil SetIntValue:aUserInfo tagKey:@"dataSize" tagIntValue:length];
		[CDictionaryUtil SetIntValue:aUserInfo tagKey:@"type" tagIntValue:0];
		if(iControlId)
			[aUserInfo setObject:iControlId forKey:@"controlId"];
		[[NSNotificationCenter defaultCenter] postNotificationName:KNotificationHttpRecvResponse object:Nil userInfo:aUserInfo];
		[aUserInfo release];
	}
	[self release];
	//[receivedData release];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSMutableDictionary *aUserInfo;
	aUserInfo=[[NSMutableDictionary alloc] init];
	NSNumber *aErrorNum=[NSNumber numberWithInt:(int)-1];
	[aUserInfo setObject:aErrorNum forKey:@"err"];
	if(iControlId)
		[aUserInfo setObject:iControlId forKey:@"controlId"];
	[[NSNotificationCenter defaultCenter] postNotificationName:KNotificationHttpRecvResponse object:Nil userInfo:aUserInfo];
	[aUserInfo release];
}

- (void)Cancel
{
	[iConnection cancel];
	//[iConnection release];
}
- (void) dealloc
{
	if(iConnection)
	{
		[iConnection cancel];
		[iConnection release];
	}
	if(iReceivedData)
	{
		[iReceivedData release];
	}
	[super dealloc];
}
@end
